package com.acoreful.acf2admin.web.servlet;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
//@MultipartConfig
@WebServlet(name = "UploadServlet", urlPatterns = {"/UploadServlet"})
public class UploadServlet extends HttpServlet{
	private Logger logger=LoggerFactory.getLogger(UploadServlet.class);
	private static final long serialVersionUID = 1L ; 

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp) ;
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response )
			throws ServletException, IOException {
		logger.info("Request ContentLength",request.getContentLength());
		String datas=request.getParameter("datas");
		System.out.println(datas);
		Part part = request.getPart("file");
		System.out.println(part);
		/*logger.info("part:{}",part.getSize());
		Collection<Part> parts=request.getParts();
		for (Part part2 : parts) {
			logger.info("part={}:{}",part2.getName(),part2.getSize());
		}
		System.out.println(parts);*/
		DiskFileItemFactory factory = new DiskFileItemFactory() ;
		factory.setSizeThreshold( 8192 ) ;
		String tempPath = request.getSession().getServletContext().getRealPath( "/")
			+ "/upload" ;  
		File file = new File( tempPath ) ;
		if(!file.isDirectory()){
			file.mkdirs();
		}
		factory.setRepository( file ) ;  
		ServletFileUpload upload = new ServletFileUpload( factory ) ;  
		 
		List<FileItem> items;
		try {
			items = upload.parseRequest(request);
			Iterator<FileItem> itr = items.iterator();   
			while (itr.hasNext()) {// 依次处理每个 form field
				   FileItem item = (FileItem) itr.next();
				   if(!item.isFormField()){  //判断是否为表单控件（非File控件），如果不是表单控件，则上传此文件 
					   File savedFile = new File( tempPath ,  item.getName() ) ;  
					   item.write(savedFile) ;
				   }else{ //如果是表单控件，则保存其值
					   System.out.println( item.getFieldName() + "-->" + item.getString() ) ; 
				   }
			}
		}catch (Exception e){
			e.printStackTrace() ; 
		}
	}
	
}
